/* eslint-disable */
import createStore from 'app/src/store/index'
import Vue from 'vue'
import { translateToken } from './assets/js/util'
import { getPermissions } from './boot/home/common-info'
import { menuListData } from './assets/js/menu-list'
import { authIntercept, goLoginNextPage, loadToken, loadChannel, saveChannel } from 'yz-help'
import { enums } from 'src/assets/js/enums'

// 初始化只执行一次
let init = true
// 不需要路由拦截的白名单
const whiteList = ['/login/password']
// 初始化 路由为三个 , 在menuList 不存在
const initRouterList = ['/main/message', '/main/home', '/main/user', '/401']
// 演示账号信息
const accountInfo = {
  dnc: {
    phone: '22222222224',
    password: '123456'
  },
  statusMonitoring: {
    phone: '22222222223',
    password: '123456'
  },
  productionExecution: {
    phone: '22222222222',
    password: '123456'
  }
}

// 路径id的对象 key: pathUrl value: id
const linkObj = {}

const huaweiEnv = loadChannel() === 'hw'
const IMCEnv = loadChannel() === 'imc'
const YQZZEnv = loadChannel() === 'yqzz'
let clientId = process.env.LOGIN_CLIENT_ID
let secret = process.env.LOGIN_CLIENT_SECRET
if (huaweiEnv) {
  clientId = 'huawei_iot_stage_app'
  secret = process.env.LOGIN_HUAWEI_CLIENT_SECRET
} else if (IMCEnv) {
  clientId = process.env.IMC_CLIENT_ID
  secret = process.env.LOGIN_IMC_CLIENT_SECRET
} else if (YQZZEnv) {
  clientId = process.env.YQZZ_CLIENT_ID
  secret = process.env.LOGIN_YQZZ_CLIENT_SECRET
}

/**
 * 获取去登录页面的方法
 */
const options = {
  authApi: process.env.AUTH_BASE_URL,
  clientId: clientId,
  loginUrl: process.env.LOGIN_BASE_URL,
  state: process.env.LOGIN_CODE_STATE
}

let goNext = goLoginNextPage(options, null, true)
/**
 * 获取link的obj key: pathUrl value: id
 */
function getRouterList (menuList) {
  const menuPage = Object.entries(enums.SYS_PERMISSION)
  if (menuList && menuList.length > 0) {
    menuList.forEach(menu => {
      const menuItem = menuPage.find(item => {
        return menu.desc === item[1].name
      })
      if (menuItem) {
        linkObj[menu.link] = menuItem[1].value
      }
      if (menu.children && menu.children.length > 0) {
        getRouterList(menu.children)
      }
    })
  }
}

getRouterList(menuListData)

export function getPermission (token, next) {
  const store = typeof createStore === 'function'
    ? createStore({ Vue })
    : createStore
  if (store.getters.permissions.length === 0) {
    // 获取userId用于获取权限映射关系
    const userInfo = translateToken(token)
    const userId = userInfo.user_id
    // 获取权限映射接口
    getPermissions(userId).then(res => {
      // 将系统权限映射存入store供按钮权限使用
      if (res.code === '1200') {
        if (res.data && res.data.length > 0) {
          let permissionList
          if (userInfo && userInfo.channel === 'hw' && userInfo.client_id === 'huawei_iot_stage_app') {
            permissionList = res.data.filter(item => [10].indexOf(item) === -1)
          } else {
            permissionList = res.data
          }
          store.commit('SET_PERMISSIONS', permissionList)
        }
        next()
      } else {
        goLoginPage()
      }
    }).catch(err => {
      console.log(err)
    })
  } else {
    next()
  }
}

export function goLoginPage (goDashboard, fullPath) {
  if (goDashboard) {
    goNext('/')
  } else {
    goNext(fullPath)
  }
}

/**
 * 演示账号自动登录
 * @param purpose 演示账号类型，通过这个加载账号密码
 * @param to vue-router to
 * @param next vue-router next
 */
function demoLogin (purpose, to, next) {
  const store = typeof createStore === 'function'
    ? createStore({ Vue })
    : createStore
  const params = accountInfo[purpose]
  // 通过vuex执行账号密码登录
  // 如果成功放行，失败的话就跳转到登录页面
  if (params) {
    store.dispatch('loginByPassword', params).then(() => {
      window.demonstrate = true
      next({ ...to, query: {} })
    }).catch(() => {
      goLoginPage(true)
    })
  } else {
    goLoginPage(true)
  }
}
/**
 * ht系统自动登录
 * @param purpose
 * @param to
 * @param next
 */
function htLogin (purpose, to, next){
  const store = typeof createStore === 'function'
    ? createStore({ Vue })
    : createStore
  const params = {
    phone: purpose?.phone,
    password: purpose?.password
  }
  // 通过vuex执行账号密码登录
  // 如果成功放行，失败的话就跳转到登录页面
  if (params) {
    store.dispatch('loginByPassword', params).then(() => {
      window.demonstrate = true
      next({ ...to, query: {} })
    }).catch(() => {
      goLoginPage(true)
    })
  } else {
    goLoginPage(true)
  }
}
const authOptions = {
  authApi: process.env.AUTH_BASE_URL,
  loginUrl: process.env.LOGIN_BASE_URL,
  baseUrl: process.env.API_BASE_URL,
  state: process.env.LOGIN_CODE_STATE,
  clientId: clientId,
  clientSecret: secret,
  whiteList: whiteList,
  goLogin: goNext,
  successCallback: () => {
    const store = typeof createStore === 'function'
      ? createStore({ Vue })
      : createStore
    store.dispatch('saveTokenData')
  }
}

export function RouterPermission (Router) {
  /**
   * 拦截器1，判断是不是测试账号,如果是注册账号的话就自动登录
   */
  Router.beforeEach((to, from, next) => {
    const { _type, _purpose } = to.query
    if (init && _type === 'demonstrate' && _purpose) {
      init = false
      demoLogin(_purpose, to, next)
    } else {
      next()
    }
  })
  /**
   * 如果是ht 登录则直接获取账号密码登录
   */
  Router.beforeEach((to, from, next) => {
    const { type } = to.query
    if (init && type === 'ht' && to.query.phone && to.query.password) {
      init = false
      htLogin(to.query, to, next)
    } else {
      next()
    }
  })
  /**
   * 拦截器5 当来源为华为是直接
   */
  Router.beforeEach((to, from, next) => {
    const { utm_source } = to.query
    // 如果url开源是华为
    if (utm_source === 'huawei') {
      saveChannel('hw')
      // 如果之前的clineId不是华为clientId
      if (options.clientId !== 'huawei_iot_stage_app') {
        // 修改option的clientId
        options.clientId = 'huawei_iot_stage_app'
        goNext = goLoginNextPage(options, null, true)
        // 修改认证的optionId
        authOptions.clientId = 'huawei_iot_stage_app'
      }
    }
    if (utm_source === 'HUA_WEI_IMC') {
      saveChannel('imc')
      // 如果之前的clineId不是华为clientId
      if (options.clientId !== process.env.IMC_CLIENT_ID) {
        options.clientId = process.env.IMC_CLIENT_ID
        // 修改认证的optionId
        authOptions.clientId = process.env.IMC_CLIENT_ID
        authOptions.clientSecret = process.env.LOGIN_IMC_CLIENT_SECRET
      }
    }
    if (utm_source === 'yqzz') {
      saveChannel('yqzz')
      // 如果之前的clineId不是华为clientId
      if (options.clientId !== process.env.YQZZ_CLIENT_ID) {
        options.clientId = process.env.YQZZ_CLIENT_ID
        // 修改认证的optionId
        authOptions.clientId = process.env.YQZZ_CLIENT_ID
        authOptions.clientSecret = process.env.LOGIN_YQZZ_CLIENT_SECRET
      }
    }
    next()
  })
  /**
   * 拦截器2，code换token
   */
  authIntercept(Router, authOptions)

  // 拦截器去掉utm_source字段
  Router.beforeEach((to, from, next) => {
    const { utm_source } = to.query
    // 构造新参数，去掉utm_source字段
    if (utm_source === 'huawei' || utm_source === 'HUA_WEI_IMC' || utm_source === 'yqzz') {
      const newQuery = {};
      const originQuery = to.query;
      Object.keys(originQuery).forEach((item) => {
        if (item !== "utm_source") {
          newQuery[item] = originQuery[item];
        }
      });
      next({...to, query: newQuery});
    }
    next()
  })

  /**
   * 拦截器3 获取权限列表
   */
  Router.beforeEach((to, from, next) => {
    const token = loadToken()
    if (token) {
      // 如果存在token
      getPermission(token, next)
    } else {
      next()
    }
  })

  /**
   * 拦截器4，拦截用户输入url进入没有权限的页面
   */
  Router.beforeEach((to, from, next) => {
    const store = typeof createStore === 'function'
      ? createStore({ Vue })
      : createStore
    // 获取permission列表
    const permissions = store.getters.permissions
    // 跳转的path
    const path = to.fullPath
    // 通过path获取到id, 如果id在permission列表中，就放行。否则拦截
    const linkId = linkObj[path]
    // 如果是能够匹配到初始化路由表，直接放行
    if (initRouterList.indexOf(path) > -1) {
      next()
    } else if (linkId) {
      // 转数字
      const id = Number(linkId)
      // 如果匹配到就放行，否则跳转401
      if (permissions.indexOf(id) > -1) {
        next()
      } else {
        next({ path: '/401' })
      }
    } else {
      // 这里放开是因为 定义了一些没传到后端的路由id
      next()
    }
  })
}
